package de.dhbw.karlsruhe.picsim.model.timer;

import de.dhbw.karlsruhe.picsim.model.cpu.ReadOnlyFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;

/**
 * Created by IntelliJ IDEA.
 * User: goesen
 * Date: Apr 28, 2010
 * Time: 7:54:05 PM
 */
final class WatchDogControl extends TimerSupport {
    private static final Log log = LogFactory.getLog(WatchDogControl.class);
    private final Timer watchdog;

    WatchDogControl(final ReadOnlyFile option, final ObservableTimer preScaler, final ObservableTimer watchdog) {
        this.watchdog = watchdog;
        preScaler.addTimeoutListener(new ObservableTimer.TimeoutListener() {
            @Override
            public void timeoutOccurred() {
                if (isPreScalerAssignedToWatchdog(option)) {
                    log.info("postScaler overflow == Timeout");
                    fireTimeout();
                }

            }
        });
        watchdog.addTimeoutListener(new TimeoutListener() {
            @Override
            public void timeoutOccurred() {
                if (isPreScalerAssignedToWatchdog(option)) {
                    log.info("Watchdog to Prescaler");
                    preScaler.increment();
                } else {
                    log.info("Watchdog and no Prescaler= TImeout");
                    fireTimeout();
                }
            }
        });
    }

    /**
     * wird bei jedem circle aufgerufen
     */
    @Override
    public void increment() {
        watchdog.increment();

    }

    static boolean isPreScalerAssignedToWatchdog(@NotNull final ReadOnlyFile option) {
        return !Timer0Control.isPreScalerAssignedToTimer(option);
    }
}
